import React, { useEffect, useState} from "react";
import type { FormInstance } from 'antd-mobile/es/components/form'
import {Col, Divider, message, Row} from "antd";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc"
dayjs.extend(utc)
import {queryFamily, queryPayment} from "@/pages/m/User/Account/settings/components/service";
import {addPayment} from "@/pages/m/Payment/service";
import {DatePicker, Form, Button, NumberKeyboard, Selector, Grid, Toast, Input} from "antd-mobile";
import PaymentLogs from "@/pages/m/PaymentLogs";
import {UnorderedListOutlined} from "@ant-design/icons";

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: any) => {
  const hide = message.loading('正在处理...');

  try {
    const res = await addPayment({...fields});
    if(res && res.status === "done"){
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    }else {
      hide()
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: "保存失败，请重试！" + error,
      icon: "fail"
    })
    return false;
  }
};
const IncomeForm: React.FC = ()=>{
  const payFormRef = React.createRef<FormInstance>()
  const [defaultType, setDefaultType] = useState<string[]>([])
  const [defaultUseBy, setDefaultUseBy] = useState<string[]>([])
  const [needUpdate, setNeedUpdate] = useState(false)

  useEffect(()=>{
    payFormRef.current?.setFieldsValue({
      payTypeId: defaultType[0],
    })
  }, [defaultType])

  useEffect(()=>{
    payFormRef.current?.setFieldsValue({
      familyTypeId: defaultUseBy[0],
    })
  }, [defaultUseBy])


  // 支出分类options
  const [typeDataSource, setTypeDatasource] = useState<any[]>([])

  // 从后台获取支出分类数据
  useEffect(() => {
    queryPayment().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...typeDataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: any)=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setDefaultType([data[0]?.value])
        setTypeDatasource(data)
      }
    })
  }, []);

  const [useByDataSource, setUseByDatasource] = useState<any[]>([])

  // 虚拟键盘同步金额
  const [money, setMoney] = useState<any>("0.00")
  const [keyboardVisible, setKeyboardVisible] = useState<boolean>(true)
  const [timePickerVisible, setTimePickerVisible] = useState<boolean>(false)

  // 虚拟键盘输入的金额同步到form中
  useEffect(() => {
    const laStr = money.substr(money.length-1, 1)
    if (laStr !== "."){
      payFormRef.current?.setFieldsValue({
        money: parseFloat(money)
      })
    }
  }, [money]);

  // 检查字符出现频率，用于限制金额输入。仅允许输入一个小数点
  function searchStrIndexOf(target: string) {
    let index = money.indexOf(target)
    let sum = 0;
    while(index > -1) {
      index = money.indexOf(target, index + 1)
      sum ++
    }
    return sum
  }

  // 设置默认的时间
  useEffect(() => {
    payFormRef.current?.setFieldsValue({
      time: dayjs(new Date()).utc().format()
    })
  }, []);

  // 从后台获取用户对象数据
  useEffect(() => {
    queryFamily().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...useByDataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: any)=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setDefaultUseBy([data[0]?.value])
        setUseByDatasource(data)
      }
    })
  }, []);

  return(
    <>
      <Grid columns={2} gap={8}>
        <Grid.Item>
          <a
            style={{color: "green", fontSize: 45,}}
            onClick={()=>{setKeyboardVisible(true)}}
          >￥{money}</a>
        </Grid.Item>
        <Grid.Item>
          <div
            style={{display: "block", height: `100%`}}
            onClick={() => {
            setKeyboardVisible(false)
            setTimePickerVisible(true)
          }}>
            <div style={{textAlign: "right", fontSize: 18}}>时间</div>
            <div style={{textAlign: "right", fontSize: 18, color: "#1677ff"}}>
              <DatePicker
                visible={timePickerVisible}
                precision='minute'
                onCancel={()=>{
                  setTimePickerVisible(false)
                }}
                onConfirm={(val)=>{
                  console.log(val.toString())
                  console.log(dayjs(val).utc().format())
                  payFormRef.current?.setFieldsValue({
                    time: dayjs(val).utc().format()
                  })
                  setTimePickerVisible(false)
                }}
              >
                {value =>
                  value ? dayjs(value).format('YYYY-MM-DD HH:mm') : dayjs(new Date()).format("YYYY-MM-DD HH:mm")
                }
              </DatePicker>
            </div>
          </div>
        </Grid.Item>
      </Grid>
      <Form
        ref={payFormRef}
        style={{
          // @ts-ignore
          "---border-bottom": "none",
        }}
        onFinish={async (value)=>{
          if (parseFloat(value.money) === 0 || isNaN(value.money)) {
            Toast.show({
              content: "请输入金额！",
              icon: "fail"
            })
          }else {

            // 提交到数据库
            const success = await handleAdd(value);
            if (success) {
              // 保存成功
              // 重置表单数据
              setMoney("0.00")
              payFormRef.current?.setFieldsValue({
                payTypeId: defaultType[0],
                familyTypeId: defaultUseBy[0],
              })
              // 更新流水
              if (needUpdate) {
                setNeedUpdate(false)
              }else {
                setNeedUpdate(true)
              }
            }
          }
          console.log(value)
        }}
      >
        <Form.Item noStyle name={"payTypeId"}/>
        <Form.Item noStyle name={"familyTypeId"}/>
        <Form.Item noStyle name={"money"}/>
        <Form.Item noStyle name={"time"}/>
        <Divider orientation={"left"}>支出分类</Divider>
        <Row style={{marginBottom: 10, marginTop: 10}}>
          <Col span={24}>
            <Selector
              key={Date.now()}
              columns={4}
              options={typeDataSource}
              defaultValue={defaultType}
              multiple={false}
              showCheckMark={false}
              style={{
                '--checked-color': "#fa541c",
                '--checked-text-color': "white",
                '--gap': "3px",
              }}
              onChange={(value)=>{
                payFormRef.current?.setFieldsValue({
                  payTypeId: value[0]
                })
              }}
            />
          </Col>
        </Row>
        <Divider orientation={"left"}>支出对象</Divider>
        <Row>
          <Col span={24}>
            <Selector
              key={Date.now()}
              columns={4}
              options={useByDataSource}
              defaultValue={defaultUseBy}
              multiple={false}
              showCheckMark={false}
              style={{
                '--checked-color': "#fa541c",
                '--checked-text-color': "white",
                '--gap': "3px",
              }}
              onChange={(value)=>{
                payFormRef.current?.setFieldsValue({
                  familyTypeId: value[0]
                })
              }}
            />
          </Col>
        </Row>
        <Divider orientation={"left"}>备注</Divider>
        <Form.Item name={"remark"} noStyle>
          <Input placeholder={"说明，备注"}/>
        </Form.Item>
        <Divider/>
        <Button
          size={"large"}
          type='submit'
          shape={"rounded"}
          style={{backgroundColor: "#fa541c", color: "white", fontSize: 15, paddingRight: 30, paddingLeft: 30}}>
           记一笔
        </Button>
      </Form>
      <NumberKeyboard
        visible={keyboardVisible}
        onInput={(value)=>{
          // 判断是否输入多个小数点
          const dotCount = searchStrIndexOf(".")
          if (dotCount === 1 && value === "."){
            return
          }

          // 判断是否是初始值
          if (money === "0.00"){
            // 初始输入时，首位不能是小数点
            if (value === "."){
              return;
            }else {
              setMoney(value)
            }
          }else {
            const moneyStr = money + value;
            setMoney(moneyStr)
          }
        }}
        onDelete={()=>{
          if (money !== "0.00"){
            const moneyStr = money.substr(0, money.length - 1)
            setMoney(moneyStr)
          }
        }}
        onClose={()=>{setKeyboardVisible(false)}}
        onConfirm={()=>{setKeyboardVisible(false)}}
        showCloseButton={true}
        customKey="."
        confirmText='确定'
      />
      <Button style={{
        backgroundColor: "#1677ff",
        color: "white",
        width: `calc(100vw - 20px)`,
        height: 58,
        marginLeft: -10,
        borderTopLeftRadius: 25,
        borderTopRightRadius: 25,
        marginTop: 16
      }}
      ><UnorderedListOutlined /> 流水清单</Button>
      <div style={{width: `calc(100vw - 40px)`}}>
        <PaymentLogs update={needUpdate}/>
      </div>
    </>
  )
}

export default IncomeForm;
